package handlers

import (
	"encoding/json"
	"github.com/gin-gonic/gin"
	"novel-world/cache"
	"novel-world/models"
	"novel-world/pkg"
	"time"
)

func UserLogin(c *gin.Context) {
	username := c.PostForm("username")
	password := c.PostForm("password")
	if username == "" || password == "" {
		c.JSON(200, gin.H{
			"code": 0,
			"msg":  "不能为空",
		})
		return
	}
	redis_key := "login_error_" + username
	errCount, _ := cache.Rdb.Get(cache.Ctx, redis_key).Int()
	if errCount >= 3 {
		c.JSON(200, gin.H{
			"code": 0,
			"msg":  "密码错误三次，禁止登录",
		})
		return
	}
	var user models.User
	models.DB.Where("username = ?", username).First(&user)
	if user.ID == 0 {
		c.JSON(200, gin.H{
			"code": 0,
			"msg":  "用户不存在",
		})
		return
	}
	if user.Password != pkg.Md5str(password) {

		cache.Rdb.Incr(cache.Ctx, redis_key)
		if errCount == 2 {
			cache.Rdb.Set(cache.Ctx, redis_key, 3, time.Hour*2)
		}
		c.JSON(200, gin.H{
			"code": 0,
			"msg":  "密码错误",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"data": user,
		"msg":  "成功",
	})
	return

}
func NovelList(c *gin.Context) {
	var novel []models.Novel
	redis_data_key := "novel_list"
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_data_key).Result()
	if cacheData == "" {
		models.DB.Find(&novel)
		jsonData, _ := json.Marshal(novel)
		cache.Rdb.Set(cache.Ctx, redis_data_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &novel)
	}
	c.JSON(200, gin.H{
		"code": 200,
		"data": novel,
		"msg":  "success",
	})
	return
}
func NovelDetail(c *gin.Context) {
	id := c.PostForm("id")
	var novel models.Novel

	redis_key := "data_detail_" + id
	cacheJson, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheJson == "" {
		models.DB.Where("id = ?", id).First(&novel)
		json, _ := json.Marshal(novel)
		cache.Rdb.Set(cache.Ctx, redis_key, json, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheJson), &novel)
	}
	c.JSON(200, gin.H{
		"code": 200,
		"data": novel,
		"msg":  "detail",
	})
	return
}
